const db = wx.cloud.database({
    env: "cloud1-9gi74drfa53d41cd"
});
const _ = db.command;
const {
    userInfo,
    isHave
} = require("../../utils/contanst");
const contanst = require("../../utils/contanst")
const app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        popShow: {
            isShow: false,
            switch: 0
        },
        userInfo: {},
        isLogin: true,
        isHave: true,
        mineTopUrl: "https://pic.imgdb.cn/item/620eff482ab3f51d91492e5f.jpg",
        infoLabel: ["../../images/nike.png", "../../images/sex.png", "../../images/qianming.png"],
    },

    //点击自己的头像进行预览
    heardImgClick: function (e) {
        console.log("预览的自己的头像图片", e.currentTarget.dataset.img)
        wx.previewImage({
            urls: [e.currentTarget.dataset.img],
        })

    },

    //点击切换背景按钮
    toggleBg: function () {
        const _this = this;
        wx.showActionSheet({
            itemList: ['从手机相册选择', '拍照'],
            success: function (res) {
                wx.chooseMedia({
                    count: 9,
                    mediaType: ['image'],
                    sourceType: ['album', 'camera'],
                    maxDuration: 30,
                    camera: 'back',
                    success(res) {
                        console.log(res)
                        const newImage = res.tempFiles[0].tempFilePath;


                        //获取缓存中的名称
                        wx.getStorage({
                            key: "userInfo",
                            success: res => {
                                console.log("getUser", res)
                                const user = res.data.nickName;

                                //更新数据库的图片
                                db.collection("user").where({
                                    userName: user
                                }).update({
                                    data: {
                                        mineTopUrl: newImage,
                                    }
                                }).then(res => {
                                    console.log(res)
                                    _this.setData({
                                        mineTopUrl: newImage
                                    })
                                    contanst.newImage = _this.data.mineTopUrl
                                    console.log(_this.data.mineTopUrl)
                                })
                            }
                        })



                    }
                })
            },
            fail: function (res) {
                console.log(res.errMsg)
            }
        })
    },

    //免责声明 点击弹出免责声明
    mzClick: function () {
        this.setData({
            popShow: {
                isShow: true,
                switch: 1
            }
        })

    },
    //联系作者
    zzClick: function () {
        console.log(10)
        this.setData({
            popShow: {
                isShow: true,
                switch: 2
            }
        })
    },
    //关闭弹出层
    onClose: function () {
        this.setData({
            popShow: {
                isShow: false,
                switch: 0
            }
        })
    },



    //退出登录
    exit: function (o) {
        console.log("退出登录")
        const _this = this;
        wx.clearStorage({
            success: (res) => {
                this.setData({
                    isLogin: true
                })
                wx.redirectTo({
                    url: "/pages/loginAndLogout/LoginAndLogout",
                    success: res => {
                        console.log("退出跳转", res)
                    }
                })


            },
        })
        wx.setStorage({
            "mineTopUrl": _this.data.mineTopUrl
        })

        contanst.loginandLogOut = {
            type: "logout",
            msg: "退出成功 点击下面链接跳转",
        }
    },
    login: function () {
        wx.getUserProfile({
            desc: '用于实现小程序登录',
            success: res => {
                console.log(res, "登录获取权限")

            },
            fail: fail => {
                console.log(fail)
            }
        })
    },

    sleep(number) {
        var now = new Date();
        var exitTime = now.getTime() + number * 1000;
        while (true) {
            now = new Date();
            if (now.getTime() > exitTime)
                return
        }
    },

    //授权
    getUserInfos: function (event) {
        console.log("授权", event.detail, event.detail.userInfo.userInfo)
        console.log(db.collection("user"))
        const that = this;


        console.log("event ", event)
        // 1.如果授权成功
        if (event.detail.userInfo.userInfo) {
            // 1.存入缓存
            wx.setStorage({
                key: "userInfo",
                data: event.detail.userInfo.userInfo
            })

          
            app.globalData.userName = event.detail.userInfo.userInfo.nickName
            //判断数据库中是否有该用户
            db.collection("user").where({
                userName: event.detail.userInfo.userInfo.nickName,
            }).get().then(res => {
                console.log("数据库中该用户的数量", res)
                if (res.data.length > 0) { // 有用户
                  
                   this.setData({
                       userInfo : res.data[0],
                       mineTopUrl : res.data[0].mineTopUrl
                   })
                  
                    this.setData({
                        isLogin : false
                    })
                } else { // 没用户
                    // 2.把数据插入到数据库
                    db.collection("user").add({
                        data: {
                            userName: event.detail.userInfo.userInfo.nickName,
                            sex: event.detail.userInfo.userInfo.gender,
                            heardUrl: event.detail.userInfo.userInfo.avatarUrl,
                            mineTopUrl: this.data.mineTopUrl
                        }
                    }).then(res => {
                        console.log("user上传数据库成功")
                        db.collection("user").where({
                            userName: event.detail.userInfo.userInfo.nickName,
                        }).get().then(res=>{
                            this.setData({
                                userInfo : res.data[0]
                            })
                        })
                        this.setData({
                            isLogin : false
                        })

                        wx.setStorage({
                            key: "isLogin",
                            data: false
                        })
                    })
                }
            })
        } else {
            // 授权失败

            //弹出提示 让用户重新授权

        }




    },


    //改头像

    changeImage(e){
        console.log( "改头像" , e)
        wx.chooseImage({
          sourceType : ['album' , "camera"],
          success : res=>{
              console.log("选择头像成功" , res.tempFilePaths[0])

              db.collection("user").where({
                  userName : this.data.userInfo.userName
              }).update({
                  data : {
                    heardUrl : res.tempFilePaths[0]
                  },
                  success : res=>{
                      console.log("修改结果 " , res)
                    db.collection("user").where({
                        userName : this.data.userInfo.userName
                    }).get().then(res=>{
                        console.log(res)
                        this.setData({
                            userInfo  : res.data[0]
                        })
                    })
                  }
              })
          }

        })
    },

    //联系作者
    lxzzClick: function () {},

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      
        console.log("调用" , this.data.isLogin)

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})